package cn.zjk.springframework.context.annotation;

import cn.hutool.core.util.StrUtil;
import cn.zjk.springframework.beans.factory.config.BeanDefinition;
import cn.zjk.springframework.beans.factory.support.BeanDefinitionRegister;
import cn.zjk.springframework.stereotype.Component;

import java.util.Set;

/**
 * @description:
 * @Author zjk
 * @className: ClassPathBeanDefinitionScanner
 * @date: 2023/4/4 14:10
 */
public class ClassPathBeanDefinitionScanner extends ClassPathScanningCandidateComponentProvider{
    private BeanDefinitionRegister register;

    public ClassPathBeanDefinitionScanner(BeanDefinitionRegister register) {
        this.register = register;
    }

    public void doScan(String... basePackages){
        for(String basePackage:basePackages){
            Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
            for(BeanDefinition beanDefinition:candidates){
                //解析Bean的作用域 singleton，prototype
                String beanScope  = resolveBeanScope(beanDefinition);
                if(StrUtil.isNotEmpty(beanScope)){
                    beanDefinition.setScope(beanScope);
                }
                register.registerBeanDefinition(determineBeanName(beanDefinition),beanDefinition);
            }
        }
    }

    private String resolveBeanScope(BeanDefinition beanDefinition) {
        Class<?> beanClass = beanDefinition.getBeanClass();
        Scope scope = beanClass.getAnnotation(Scope.class);
        if (null != scope) {
            return scope.value();
        }
        return StrUtil.EMPTY;
    }

    private String determineBeanName(BeanDefinition beanDefinition) {
        Class<?> beanClass = beanDefinition.getBeanClass();
        Component component = beanClass.getAnnotation(Component.class);
        String value = component.value();
        if (StrUtil.isEmpty(value)) {
            value = StrUtil.lowerFirst(beanClass.getSimpleName());
        }
        return value;
    }
}
